package dao;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import bean.User;
import database.PersistenceUtil;
import exception.UserNotFoundException;

public class UserDao {
	private static final Logger LOGGER = Logger.getLogger(UserDao.class);

	public static boolean verifyUser(String userName, String pass)
			throws Exception {
		EntityManager conn = PersistenceUtil.getEntityManager();
		try {
			Query q = conn.createNamedQuery("User.findByUser", User.class);
			q.setParameter("userName", userName);
			User u = (User) q.getSingleResult();

			if (u == null) {
				throw new UserNotFoundException();
			}

			if (u.getPassword().equals(pass)) {
				return true;
			}
		} catch (Exception e) {
			throw e;
		} finally {
			conn.close();
		}
		return false;
	}

	public void createUser(String userName, String pass, String email,
			String country) throws Exception {
		EntityManager conn = PersistenceUtil.getEntityManager();
		try {
			conn.getTransaction().begin();
			User user = new User(userName, pass, email, country);
			conn.persist(user);
			conn.getTransaction().commit();
		} catch (Exception e) {
			LOGGER.error("Error while creating user : user=" + userName
					+ " ,pass=" + pass + " ,email= " + email + ", country="
					+ country + "\n" + e.getMessage());
			conn.getTransaction().rollback();
			throw e;
		} finally {
			LOGGER.info("User created : user=" + userName + " ,pass=" + pass
					+ " ,email= " + email + ", country=" + country);
			conn.close();
		}
	}
}
